// documents here...
define(['./PageView', "jquery", '../libs/AjaxUtil', '../libs/scrollBottom', '../libs/CommonTools'], function (PageView, $, AjaxUtil, ScrollBottom, Common) {
    require('../../less/AllOKRs.less');

    return PageView.extend({

        events: {
            'click .log-head-left': 'goBack',
            'click .launch-btn': 'launch',
            'click .js-to-detail': 'toDetail',
            'click .add-okrs-button': 'addOkrs',
            'click .left': 'closeWindow',
            'click .select-left-list li': 'selectLeftItem',
            'click .select-right-list li': 'selectRightItem',
        },
        default: true,
        closeWindow: function () {
            var data = {function: 'closePage'};
            window.WebViewJavascriptBridge.send(JSON.stringify(data), function (responseData) {
            });
        },

        toDetail: function (e) {
            var id = $(e.currentTarget).attr('id');
            Backbone.history.navigate('#OKRsDetail?target_id=' + id, {trigger: true});
        },

        initialize: function () {
            var _this = this;
            var selectView = _this.findComponent('OKRsSelectView');
            _this.selectView = selectView;
            _this.count = 10;
            this.scrollBottom = new ScrollBottom();
            this.tabClassName = {};

            this.params = {
                ownerType: 1,
                pageNo: 1
            };

        },
        render: function () {
            PageView.prototype.render.apply(this, arguments);
            this.$wrap = $('<div class="main"><div class="content"></div></div><div class="add-okrs"><div class="add-okrs-button"><i class="icon-add add-icon"></i>新建目标</div></div>');
            this.$el.append(this.$wrap);
            return this;
        },
        onResume: function () {
            var deptObj = JSON.parse(sessionStorage.getItem('SELECTED_DEPT'));

            if (deptObj) {
                this.selectFromDeptList(deptObj);
            } else {
                this.updateList(this.params);
            }
        },
        _getTeamData: function () {
            var _this = this;
            var tpl = '';
            AjaxUtil.ajaxGet({
                path: "/client/dept/my", success: function (res) {
                    if (res.length != 0) {
                        res.forEach(function (it) {
                            if (it.deptId !== 0 || it.deptName !== '') {
                                tpl += '<li class="myTeam" val="' + it.deptId + '" > ' + it.deptName + '</li>';
                            }
                        });
                        tpl += '<li class="other-dept" val="2" >查看其他部门<span class="other-dept-name"></span><span class="arrow-right"><i class="icon-right"></i></span></li>';
                        tpl += '<li class="other-person" val="1" >查看其他同事<span class="other-person-name"></span><span class="arrow-right"><i class="icon-right"></i></span></li>';

                        _this.selectView.$el.find('.select-left-list').append(tpl);
                    }
                }, dataEmpty: function () {

                }
            });
        },
        _getJournalTpl: function () {
            var _this = this;
            var tpl = '';
            AjaxUtil.ajaxGet({
                path: "/client/cycle/selector", success: function (res) {
                    var thisCycle = '',
                        thisCycleId = '';
                    res.forEach(function (it) {
                        if (it.isNow == 0) {
                            tpl += '<li  val="' + it.cycleId + '" class="selected" > ' + it.cycle + '</li>';
                            thisCycle = it.cycle;
                            thisCycleId = it.cycleId;
                        } else {
                            tpl += '<li  val="' + it.cycleId + '" > ' + it.cycle + '</li>';
                        }
                    });
                    _this.selectView.$el.find('.select-right-list').append(tpl);

                    _this.selectView.$el.find('.select-title li:last-child span').html(thisCycle);
                    _this.params.cycleId = thisCycleId;

                    _this._getFirstData();

                }, dataEmpty: function () {

                }
            });
        },
        scrollGetMore: function () {
            var _this = this;
            this.scrollBottom.scrollGetMore(_this.$el.find('.main')[0], 50);
            _this.$el.find('.main').on('scrollBottom', function (e) {

                if (_this.scrollBottom.hasNext && !_this.scrollBottom.isLoading && $(e.currentTarget)
                        .parent().attr('id') == _this.$el.attr('id')) {

                    _this.scrollBottom.isLoading = true;

                    var xhr = AjaxUtil.ajaxGetDeferred({
                        path: '/client/objective/search',
                        params: _this.params
                    });
                    xhr.done(function (d) {
                        _this.params.pageNo += 1;
                        _this.count += 10;
                        var $wrap = _this.$wrap.find('.content');
                        var temp = '';
                        d.forEach(function (it) {
                            var tpl = require('../templates/allOKRs/item.html');
                            temp += _.template(tpl)(it);
                        });
                        $wrap.append(temp);
                    }).fail(function (d) {

                        if (d.code == 100220005) {

                            var container = _this.el.getElementsByClassName('main');
                            _this.scrollBottom.scrollToBottom(container);
                            _this.scrollBottom.hasNext = false;
                        } else {
                            Common.Toast(d.msg);
                        }
                    }).always(function (d) {
                        _this.scrollBottom.isLoading = false;
                    });
                }
            });
        },
        onRender: function () {
            this._getTeamData();
            this._getJournalTpl();
            return this;
        },
        _getFirstData: function () {
            var _this = this;
            _this.params.pageNo = 1;

            AjaxUtil.ajaxPost({
                path: '/client/objective/search', params: this.params, success: function (data) {
                    _this.params.pageNo = 2;
                    var $wrap = _this.$wrap.find('.content');
                    _this.data = data;
                    data.forEach(function (it) {
                        var temp = require('../templates/allOKRs/item.html');
                        temp = _.template(temp)(it);
                        $wrap.append(temp);
                    });
                    _this.scrollGetMore();
                }
            });
        },
        goBack: function () {
            window.history.back();
        },
        launch: function (e) {
            var $this = $(e.target);
            if ($this.hasClass('expand-btn')) {
                $this.parent().prev().children('.log-item-main').css({
                    'max-height': 'initial',
                    'overflow': 'visible'
                });
            } else {
                $this.parent().prev().children('.log-item-main').css({
                    'max-height': '',
                    overflow: ''
                });
            }
            $this.hide().siblings().show();
        },
        updateList: function (val) {
            var _this = this;

            if (val && val.cycleId) {
                _this.params.cycleId = val.cycleId;
            }
            if (val && val.deptId) {
                _this.params.deptId = val.deptId;
            } else {
                delete _this.params.deptId;
            }
            if (val && val.createId) {
                _this.params.createId = val.createId;
            } else {
                delete _this.params.createId;
            }

            _this.params.pageNo = 1;

            _this.searchObjective();
        },
        searchObjective: function () {
            var _this = this;

            AjaxUtil.ajaxGet({
                path: '/client/objective/search', params: _this.params, success: function (data) {
                    _this.params.pageNo = 2;

                    var $wrap = _this.$wrap.find('.content');
                    _this.data = data;
                    var temp = '';
                    data.forEach(function (it) {
                        var tpl = require('../templates/allOKRs/item.html');
                        temp += _.template(tpl)(it);
                    });
                    $wrap.html(temp);

                }, dataEmpty: function () {
                    _this.$wrap.find('.content').html("");
                }
            });
        },
        addOkrs: function (e) {
            Backbone.history.navigate('#GoalAddNEdit', {trigger: true});
        },
        goDeptList: function () {
            Backbone.history.navigate('#SelectDeptList', {trigger: true});
        },
        goPersonList: function () {
            var _this = this;
            var data = {
                function: "selectContacts",
                parameters: {
                    multi: 0,
                    nav_title: "选择其他同事",
                    nav_color: "#ffffff"
                }
            };

            window.WebViewJavascriptBridge.send(JSON.stringify(data), function (responseData) {
                var userData = JSON.parse(responseData);
                // var userData = {
                //     _id: 0,
                //     avatar: "http://staticoss.upesn.com/5417/2834476/201606/10/1465562343e38f8ee7318fc6ed110de7bb896d5f7f.jpeg.thumb.jpg",
                //     id: 2834476,
                //     in_qz: 0,
                //     is_caller: 0,
                //     member_id: 2834476,
                //     member_type: 0,
                //     name: "刘成裕",
                //     tel: "13786178379",
                //     type: 0
                // };
                if (userData && userData.data.length > 0) {
                    _this.selectFromPersonList(userData.data[0]);
                }
            });
        },
        selectLeftItem: function (e) {
            var _this = this,
                $target = $(e.currentTarget),
                leftVal = '',
                rightVal = '',
                val = {};

            this.tabClassName.left = $target.attr('class');

            if (this.tabClassName.left.indexOf('other-dept') > -1) {
                this.params.ownerType = 2;
                $target.addClass('selected-other-dept');
                _this.goDeptList();
            } else if (this.tabClassName.left.indexOf('other-person') > -1) {
                $target.addClass('selected-other-person');
                _this.goPersonList();
                this.params.ownerType = 1;
            } else {

                this.resetLeftData();
                $target.addClass('selected');
                this.selectView.selectComplete(e);

                // 我的
                if (this.tabClassName.left.indexOf('me') > -1) {
                    this.params.ownerType = 1;
                    // 不阻止updateList校验
                    _this.params.deptId = leftVal = '';
                    // 我的部门
                } else if (this.tabClassName.left.indexOf('myTeam') > -1) {
                    this.params.ownerType = 2;
                    leftVal = this.$el.find('.select-left-list .selected').attr('val');
                }

                rightVal = this.$el.find('.select-right-list .selected').attr('val');

                val = {
                    deptId: leftVal,
                    cycleId: rightVal,
                };

                this.updateList(val);
            }
        },
        selectRightItem: function (e) {
            var $target = $(e.currentTarget),
                leftVal = '',
                rightVal = '',
                val = {};

            this.$el.find('.select-right-list li').removeClass('selected')
                .removeClass('selected-other-dept').removeClass('selected-other-person');
            $target.addClass('selected');
            this.selectView.selectComplete(e);

            leftVal = this.$el.find('.select-left-list .selected').attr('val');
            rightVal = this.$el.find('.select-right-list .selected').attr('val');
            val = {
                deptId: leftVal,
                cycleId: rightVal,
            };

            this.updateList(val);
        },
        selectFromDeptList: function (deptObj) {
            this.resetLeftData();
            this.$el.find('.select-title li:first span').html(deptObj.deptName);
            this.$el.find('.other-dept-name').html(deptObj.deptName);

            this.selectView.hideMask();

            var leftVal = deptObj.deptId;
            var rightVal = this.$el.find('.select-right-list .selected').attr('val');
            var val = {
                deptId: leftVal,
                cycleId: rightVal,
            };

            sessionStorage.removeItem('SELECTED_DEPT');

            this.updateList(val);
        },
        selectFromPersonList: function (personObj) {
            this.resetLeftData();
            this.$el.find('.select-title li:first span').html(personObj.name);
            this.$el.find('.other-person-name').html(personObj.name);

            this.selectView.hideMask();

            var leftVal = '';
            var rightVal = this.$el.find('.select-right-list .selected').attr('val');
            var val = {
                deptId: leftVal,
                cycleId: rightVal,
                createId: personObj.member_id
            };

            this.updateList(val);
        },
        // 重置左选项数据
        resetLeftData: function () {
            this.$el.find('.select-left-list li').removeClass('selected')
                .removeClass('selected-other-dept').removeClass('selected-other-person');

            this.$el.find('.other-dept-name').html('');
            this.$el.find('.other-person-name').html('');
        }
    });
});
